package cn.kawa.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

@Component
public class LoginCheckFilter extends ZuulFilter {
    /**
     * 指定当前过滤器在什么时候执行
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }
    //filter执行顺序，数字越小越先，一般不用负数
    @Override
    public int filterOrder() {
        return 0;
    }
    //此方法判断是否要执行目标方法run
    @Override
    public boolean shouldFilter() {
        //1.得到请求的上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //2.得到当前请求的uri
        String uri = currentContext.getRequest().getRequestURI();
        //3.判断是否访问路径包含login信息
        if(StringUtils.endsWithIgnoreCase(uri,"login")||StringUtils.endsWithIgnoreCase(uri,"register")){
            return false;
        }

        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //1.得到token
        String token = RequestContext.getCurrentContext().getRequest().getHeader("token");
        //获取response对象并对其设置编码
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        response.setContentType("application/json;charset=utf-8");
        //2.判断token是否为null
        if(StringUtils.isEmpty(token)){//为空就返回未登录的json信息
            try {//将未登录信息存到map并转换为jsonString
                HashMap<String, Object> map = new HashMap<>();
                map.put("success",false);
                map.put("message","noLogin");
                String jsonString = JSONObject.toJSONString(map);
                //通过response获取writer，并写jsonString到前端
                PrintWriter writer = response.getWriter();
                writer.write(jsonString);
                //阻止后续的filter执行：利用currentContext的setSendZuulResponse方法
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return "随便都行";
    }
}
